/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sirtet.tetris.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import sirtet.gui.PiecePanel;
import sirtet.tetris.TetrisPiece;

/**
 * A panel that can show a TetrisPiece
 * @author guangwei.zhu
 */
public class TetrisPiecePanel extends PiecePanel {

    @Override
    protected void renderBlock(Graphics g, Object block, Point point, Dimension size) {
        int element = (Integer) block;

        if (element != TetrisPiece.EMPTY) {
            g.setColor(pieceColor);
            g.fill3DRect(point.x, point.y, size.width, size.height, true);
        } else {
            g.setColor(this.getBackground());
            g.fillRect(point.x, point.y, size.width, size.height);
        }
    }
    
    @Override
    public void paintComponent(Graphics g)
    {
        if (this.squareShaped)
        {
            if (this.getWidth() != this.getHeight())
            {
                this.setSize(this.getWidth(), this.getWidth());
            }
        }

        super.paintComponent(g);
    }

    public void setPieceColor(Color pieceColor) {
        this.pieceColor = pieceColor;
        this.repaint();
    }

    public Color getPieceColor() {
        return this.pieceColor;
    }

    public void setSquareShaped(boolean squareShaped) {
        this.squareShaped = squareShaped;

        if (squareShaped) {
            this.addComponentListener(squareEnforcer);
        } else {
            this.removeComponentListener(squareEnforcer);
        }
    }

    @Override
    public void setSize(Dimension size) {
        if (squareShaped) {
            size.height = size.width;
        }

        super.setSize(size);
    }

    @Override
    public void setSize(int width, int height) {
        if (squareShaped) {
            height = width;
        }

        super.setSize(width, height);
    }

    @Override
    public void setPreferredSize(Dimension size) {
        if (squareShaped) {
            size.height = size.width;
        }

        super.setPreferredSize(size);
    }
    protected boolean squareShaped;
    protected Color pieceColor;
    private ComponentAdapter squareEnforcer = new ComponentAdapter() {

        private boolean reentry = false;

        @Override
        public void componentResized(ComponentEvent evt) {
            // Make sure the panel is always square-shaped
            if (reentry) {
                return;
            }
            reentry = true;

            Dimension size = new Dimension(getWidth(), getWidth());
            setSize(size);
            setPreferredSize(size);

            reentry = false;
        }
    };
}
